<?php
// 接口-客户管理
namespace interface\v1;

use verify;

class clientAppClass extends index
{
	private const title       = '客户';
	private const page        = 'client';
	private const table       = 'kehu';
	private const tableStaff  = 'kehu_staff';
	private const defaultPool = 'defaultClientPool';//默认客户池ID
	
	
	public function search()
	{
		$this->code = 1;
		$tag        = [];
		$array      = self::sqlFind("SELECT DISTINCT name, list FROM `tag_detail` WHERE 1=1 ORDER BY list asc");
		foreach ($array as $item) {
			unset($item['list']);
			$tag[] = $item;
		}
		$tag                = array_column($tag, 'name');
		$this->resp['data'] = [
			'orderBy'  => [
				'跟进时间升序',
				'跟进时间降序',
				'创建时间升序',
				'创建时间降序',
				'更新时间降序',
				'更新时间升序',
			],
			'belong'   => ['我的客户', '我协作的', '所有客户'],
			'workFlow' => explode("，", para("clientWorkFlow")),
			'source'   => explode("，", para("clientSource")),
			'tag'      => $tag,
		];
	}
	
	public function params()
	{
		$this->code = 1;
		$type       = $this->post('type');
		$data       = [];
		switch ($type) {
			case 'nature': # 客户性质
			case 'workFlow': # 跟进状态
			case 'level': # 客户级别
			case 'type': # 客户类别
			case 'industry': # 所属行业
			case 'scale': # 人员规模
			case 'source': # 客户来源
				// 首字母大写
				$type = ucfirst($type);
				$data = explode('，', para('client' . $type));
				break;
			case 'followQuick': # 跟进方式
				$data = explode('，', para($type));
				break;
			case 'remindTime': # 提醒
				$data = ['15分钟前', '无', '日程开始时', '1小时前', '1天前'];
				break;
			case 'tag':
			case 'tags': # 标签
				$array = self::sqlFind("SELECT d.id,t.name as tagName, d.name as name FROM `tag_detail` as d, `tag` as t WHERE d.orderId = t.id ORDER BY t.name asc;
");
				foreach ($array as $item) {
					$temp = $item;
					unset($temp['tagName']);
					$data[$item['tagName']]['title']   = $item['tagName'];
					$data[$item['tagName']]['array'][] = $temp;
				}
				$data = array_values($data);
				break;
			case 'pool': #公客池
				$data = find([
					'field' => 'id as value, name as text',
					'table' => 'pool',
					'where' => " type='公客池' ",
				])['array'];
				break;
			case 'staff': # 员工
				$data = find([
					'field' => 'stid as value, name as text',
					'table' => 'staff',
				])['array'];
				break;
			case 'belong': #客户归属
				$data = ['我的客户', '我协作的', '所有客户'];
				break;
		}
		$this->resp['data'] = $data;
	}
	
	/**
	 * 列表
	 *
	 * @return void
	 */
	public function list()
	{
		$belong = $this->post('belong') ?: '我的客户';
		$where  = " data_source = 0 ";
		if ($this->post('pageType') === 'choose') {
			$where .= " AND (manager = '" . self::$stid . "' OR collaborator = '" . self::$stid . "') ";
		} else {
			$where .= match ($belong) {
				'我的客户'  => " and manager = '" . self::$stid . "' ",
				'我协作的'  => " and collaborator = '" . self::$stid . "' ",
				default => " and manager <> '' ",
			};
		}
		// 所有客户
		if ($belong == '所有客户') {
			if ($this->power(self::page, "seeAll")) {
				//查看所有客户的权限
				$where .= " and 1=1";
			} elseif ($this->power(self::page, "seeGroup")) {
				//查看本组（直接下级）
				$where .= " and (collaborator like '%" . self::$stid . "%'  or manager = '" . self::$stid . "' or manager in (select stid from staff where manager = '" . self::$stid . "'))";
			} else {
				//查看自己
				$where .= " and (collaborator like '%" . self::$stid . "%'  or manager = '" . self::$stid . "')";
			}
		}
		// 关键字搜索
		if ($this->post('wd')) {
			$wd    = $this->post('wd');
			$where .= " AND (companyName like '%$wd%' OR contactName like '%$wd%' OR contactTel like '%$wd%' ) ";
		}
		//获取查询结果
		$where   .= search([
			"="    => [
				'workFlow' => $this->post('workFlow'),
				'source'   => $this->post('source'),
			],
			'like' => [
				'tags' => $this->post('tag'),
			],
		]);
		$orderBy = $this->orderBy([
			"search"  => $this->post('orderBy') ?: null,
			"default" => "创建时间降序",
			"array"   => [
				"lastFollowTime" => ["asc" => "跟进时间升序", "desc" => "跟进时间降序", "site" => 1],
				"time"           => ["asc" => "创建时间升序", "desc" => "创建时间降序", "site" => 2],
				"updateTime"     => ["asc" => "更新时间升序", "desc" => "更新时间降序", "site" => 3],
			],
		]);
		$page    = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy'],]);
		//数据分析
		$data['result'] = [];
		foreach ($page['array'] as $array) {
			$data['result'][] = [
				"khid"        => $array['khid'],
				'companyName' => $array['companyName'],
				'tags'        => self::filterArray(explode(',', $array['tags'])),
				'contactName' => $array['contactName'],
				'contactTel'  => $array['contactTel'],
				"workFlow"    => $array['workFlow'],
				'source'      => $array['source'],
				'time'        => self::formatDate($array['time'], 'Y/m/d'),
			];
		}
		$data['page']    = $page['para'];
		$data['belong']  = $belong;
		$data['orderBy'] = '创建时间降序';
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	/**
	 * 转交客户
	 *
	 * @return void
	 */
	public function transferEdit()
	{
		$this->code = 0;
		$listId     = $this->post('khid') ? [$this->post('khid')] : $this->post('listId');
		$field      = [
			'manager'      => $this->post('manager'),
			'collaborator' => $this->post('manager') ?: [],
		];
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '您还没有' . self::title . '的编辑权限';
		} elseif (empty($listId) || !is_array($listId)) {
			$this->resp['warn'] = '请选择转交客户';
		} elseif (empty($this->post('manager'))) {
			$this->resp['warn'] = '请选择负责人';
		} else {
			$x = 0;
			//查看范围
			$seeArr                = array_merge([$field['manager']], (is_array($field['collaborator']) ? $field['collaborator'] : explode(',', $field['collaborator'])));
			$field['see']          = implode(',', self::filterArray($seeArr));
			$field['collaborator'] = empty($field['manager']) ? '' : $field['collaborator'];
			$manager               = query('staff', "stid = '$field[manager]'");
			foreach ($listId as $id) {
				$info = query(self::table, " khid = '$id'");
				if ($info['manager'] != $field['manager'] && ($info['manager'] == self::$stid || $this->power(self::page, 'admin'))) {
					$warn = static::update([
						'table' => self::table,
						'field' => $field,
						'where' => " khid = '$id'",
					]);
					if ($warn == '更新成功') {
						$x++;
						static::insert([
							'table' => 'clue_log',
							'field' => [
								'id'        => self::getId(),
								'orderId'   => $id,
								'classify'  => '客户',
								'type'      => '转交',
								'text'      => $this->control['name'] . "转交了" . self::title . "【{$info['companyName']}】给负责人：" . $manager['name'],
								'staffName' => $this->control['name'],
								'stid'      => $this->control['stid'],
								'time'      => $this->time,
							],
						]);
						$text = $this->control['name'] . "转交了" . self::title . "【{$info['companyName']}】， id：【" . $id . '】给负责人：' . $manager['name'];
						
						$this->logText(["type" => self::page, "text" => $text]);
					}
				} else {
					$text = $this->control['name'] . "转交" . self::title . "【{$info['companyName']}】失败：不是负责人或转交的人和此客户负责人相同";
					$this->logText(["type" => self::page, "text" => $text]);
				}
			}
			$this->code         = 1;
			$this->resp['warn'] = "成功转交" . $x . '条数据，详情请查看日志';
		}
		
		resp:
	}
	
	/**
	 * 新增客户
	 *
	 * @return void
	 */
	public function editEdit()
	{
		$this->code = 0;
		$id         = $this->post('khid') ?: self::getId();
		$labelMxId  = $this->post('tagId') ? explode(',', $this->post('tagId')) : [];//标签ID
		$field      = [
			"contactName"     => $this->post('contactName'),//联系人姓名
			"contactIdentity" => $this->post('contactIdentity'),//联系人身份
			"contactTel"      => $this->post('contactTel'),//联系人手机号码
			"contactQQ"       => $this->post('contactQQ'),//联系人QQ号码
			"contactWx"       => $this->post('contactWx'),//联系人微信号
			"address"         => $this->post('address'),
			"birthDay"        => $this->post('birthDay'),
			"website"         => $this->post('website'),
			"email"           => $this->post('email'),
			"nature"          => $this->post('nature'),
			"invoiceCompany"  => $this->post('invoiceCompany'),
			"postAddress"     => $this->post('postAddress'),
			"workFlow"        => $this->post('workFlow'),//跟进状态
			"source"          => $this->post('source'),//客户来源
			"level"           => $this->post('level'),
			"classify"        => $this->post('classify'),
			"scale"           => $this->post('scale'),
			'followTime'      => $this->post('followTime'),
			"industry"        => $this->post('industry'),//所在行业
			"text"            => $this->post('text'),
			"companyName"     => $this->post('companyName'),//公司名称
			"companyNum"      => $this->post('companyNum'),//纳税人识别号
			"companyBank"     => $this->post('companyBank'),//公司开户银行
			"companyBankNum"  => $this->post('companyBankNum'),//对公账号
			"landline"        => $this->post('landline'),//公司座机
			"companyAddress"  => $this->post('companyAddress'),//开票地址
			'poolId'          => $this->post('poolId') ?: self::defaultPool,
			'manager'         => $this->post('manager') ?: self::$stid,
			'region'          => '',
			'collaborator'    => $this->post('collaborator') ?: '',
		];
		$annotation = [
			'companyName' => '客户名称',
			'contactName' => '常用联系人',
			'nature'      => '性质',
			"contactTel"  => '手机号码',
			'manager'     => '负责人',
		];
		$rules      = [
			'companyName' => 'required',
			'contactName' => 'required',
			'nature'      => 'required',
			"contactTel"  => 'required|tel',
			'manager'     => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where  = " khid = '$id' ";
		$info   = query(self::table, $where);
		$repeat = [
			"khid"  => $id,
			"field" => $field,
			"name"  => ["contactTel" => "联系人手机号码", "contactQQ" => "联系人QQ", "companyName" => "公司名称", "companyNum" => "纳税人识别号"],
		];
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
			$this->resp['warn'] = '邮箱格式错误';
		} elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
			$this->resp['warn'] = 'QQ号码格式错误';
		} elseif (!empty($field['website']) && preg_match(checkUrl, $field['website']) == 0) {
			$this->resp['warn'] = '网址格式错误';
		} elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
			$this->resp['warn'] = '所选的协作人中包含了负责人';
		} elseif (!empty($info['khid']) && !in_array($this->control['stid'], explode(",", $info['see']))) {
			$this->resp['warn'] = "这不是你的客户，你也不是协作人";
		} elseif ($warn = $this->repeat($repeat)) {
			$this->resp['warn'] = $warn;
		} elseif (self::total(array('table' => self::table, 'where' => "companyName = '$field[companyName]' and khid !='$id'")) > 0) {
			$this->resp['warn'] = '已存在此客户名称';
		} else {
			//查看范围
			$field['see'] = implode(',', array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
			if ($this->post('location')) {
				$location     = explode(',', $this->post('location'));
				$field['lat'] = $location[0];
				$field['lng'] = $location[1];
				$region       = self::coordinateToAddr($field['lat'], $field['lng']);
				if ($region['err_code'] == 0) {
					$field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
				}
			}
			
			if (!$info['khid']) {
				$userNo             = self::generateCode(self::page,[
                    'prefix' => 'C',
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ],$field);
				$field              = array_merge($field, [
					'khid'    => $id,
					'orderNo' => $userNo,
					'stid'    => $this->control['stid'],
					'time'    => $this->time,
				]);
				$this->resp['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$this->resp['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				$tagsText = '';
				//添加标签
				$kehuLabelId = [];
				if (!empty($labelMxId) && is_array($labelMxId)) {
					foreach ($labelMxId as $tagsId) {
						$kehu_label = query('kehu_label', "targetId = '$id' and tag_detail_id = '$tagsId'");
						$tagsDetail = query('tag_detail', "id = '$tagsId'");
						$tags       = query('tag', "id = '$tagsDetail[orderId]'");
						$tagsText   .= $tagsDetail['name'] . ',';
						if (empty($kehu_label['id'])) {
							$mid           = self::getId();
							$kehuLabelId[] = $mid;
							static::insert([
								'table' => 'kehu_label',
								'field' => [
									'id'            => $mid,
									'targetId'      => $id,
									'tag_detail_id' => $tagsId,
									'tagId'         => $tags['id'],
									'type'          => 1,
									'time'          => $this->time,
								],
							]);
						} else {
							$kehuLabelId[] = $kehu_label['id'];
						}
					}
				}
				//删除无效关联的标签
				delete(['table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehuLabelId) . "') and targetId = '$id'"]);
				update(['table' => self::table, 'field' => ['tags' => $tagsText], 'where' => "khid = '$id'"]);
				//常用联系人添加到联系人中
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logWrite($id, $type);
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code = 1;
			}
		}
		
		resp:
	}
	
	/**
	 * 客户联系人
	 *
	 * @return void
	 */
	public function staffList()
	{
		$where = ' 1=1 ';
		if (!$this->power(self::page, 'seeAll')) {
			$where .= " and a.stid = '" . self::$stid . "'";
		}
		$wd = $this->post('wd');
		if ($wd) {
			$where .= " AND (b.companyName like '%$wd%' OR a.name like '%$wd%' OR a.tel like '%$wd%' ) ";
		}
		$this->code         = 1;
		$page               = $this->page([
			'field' => " a.*, b.companyName",
			"table" => "kehu_staff as a join kehu as b on a.khid = b.khid",
			"where" => $where,
			"order" => "a.updateTime desc",
		]);
		$data['result']     = $page['array'];
		$data['page']       = $page['para'];
		$this->resp['data'] = $data;
	}
	
	/**
	 * 新增修改联系人
	 *
	 * @return void
	 */
	public function staffEdit()
	{
		$khid = $this->post('khid');
		$id   = $this->post('id') ?: self::getId();
		//赋值
		$field      = [
			'khid'       => $this->post('khid'),
			"sex"        => $this->post('sex'),
			"position"   => $this->post('position'),//职位
			"name"       => $this->post('name'),//姓名
			"department" => $this->post('department'),
			"birthDay"   => $this->post('birthDay'),
			"tel"        => $this->post('tel'),//手机
			"phone"      => $this->post('phone'),//座机
			"qq"         => $this->post('qq'),//QQ号码
			"WeChat"     => $this->post('WeChat'),//微信号
			"address"    => $this->post('address'),//排序号
			"text"       => $this->post('text'),//备注
		];
		$annotation = [
			'khid' => "客户",
			"sex"  => '性别',
			"name" => '姓名',
			"tel"  => '手机',
		];
		$rules      = [
			"khid" => 'required',
			"sex"  => 'required',
			"name" => 'required',
			"tel"  => 'required|tel',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		$kehu   = query('kehu', " khid = '$khid' ");
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
		} elseif (!$this->power("client", "staffEdit")) {
			$this->resp['warn'] = "您没有编辑客户联系人的权限";
		} elseif (sqlNum("kehu_staff", " tel = '$field[tel]' and khid = '$kehu[khid]' and id != '$id' ") > 0) {
			$this->resp['warn'] = "此客户的联系人中已经存在本手机号码了";
		} elseif (!empty($field['qq']) and preg_match(checkInteger, $field['qq']) == 0) {
			$this->resp['warn'] = "QQ号码必须为正整数";
		} else {
			$kehuStaff = query('kehu_staff', " id = '$id' ");
			if (empty($kehuStaff['id'])) {
				$field              = array_merge($field, [
					"id"   => $id,
					"stid" => self::$stid,
				]);
				$this->resp['warn'] = static::insert(["table" => "kehu_staff", "field" => $field]);
			} else {
				$this->resp['warn'] = static::update(["table" => "kehu_staff", "field" => $field, "where" => " id = '$kehuStaff[id]' "]);
			}
			
			if (in_array($this->resp['warn'], array("新增成功", "更新成功"))) {
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . "为客户【" . $kehu['companyName'] . "】【客户ID：" . $kehu['khid'] . "】" . $type . "了一个客户联系人：" . $field['name'] . "ID号：" . $this->post('id');
				$this->logText(["type" => "client", "text" => $text]);
				$this->code = 1;
			}
		}
		resp:
	}
	
	/**
	 * 客户跟进记录
	 *
	 * @return void
	 */
	public function followList()
	{
		$where = " target='客户' ";
		if (!$this->power(self::page, 'seeAll')) {
			$where .= " AND stid = '" . self::$stid . "'";
		}
		$wd = $this->post('wd');
		if ($wd) {
			if (is_numeric($wd)) {
				$where .= " AND targetId in (SELECT khid FROM `kehu_staff` WHERE tel like '%$wd%' ) ";
			} else {
				$where .= " AND (contactName like '%$wd%' OR targetName like '%$wd%' ) ";
			}
		}
		$this->code = 1;
		$page       = $this->page([
			'field' => '`id`, `stid`, `targetName`, `contactName`, `followType`, `text`, `time`',
			"table" => "follow",
			"where" => $where,
			"order" => "time desc",
		]);
		$result     = [];
		foreach ($page['array'] as $item) {
			$staff             = query('staff', " stid = '{$item['stid']}' ");
			$item['ico']       = root . $staff['ico'];
			$item['staffName'] = $staff['name'];
			$item['date']      = self::formatDate($item['time'], 'm月d日 H:i');
			$result[]          = $item;
		}
		$data['result']     = $result;
		$data['page']       = $page['para'];
		$this->resp['data'] = $data;
	}
	
	/**
	 * 客户跟进
	 *
	 * @return void
	 */
	public function followEdit()
	{
		$startDay = $this->post('startDay'); //  下次跟进日期
		//赋值
		$field      = [
			"id"          => self::getId(),
			"stid"        => self::$stid,
			"target"      => '客户',
			"targetId"    => $this->post('khid'),
			'kehuStaffId' => $this->post('kehuStaffId'), // 客户联系人id
			"text"        => $this->post('text'), // 跟进内容
			"followType"  => $this->post('followType'), // 跟进方式
		];
		$annotation = [
			"targetId"    => '跟进对象',
			"text"        => '跟进内容',
			"kehuStaffId" => '客户联系人',
			"followType"  => '跟进方式',
		];
		$rules      = [
			"targetId"    => 'required',
			"text"        => 'required',
			"kehuStaffId" => 'required',
			"followType"  => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			return;
		}
		
		$backlogType   = $field['target'] . "跟进";                            //待办事项类型
		$followText    = $field['text'] . "【" . $this->control['name'] . "】";//添加后缀，防止管理员被删除后无法通过管理员id查询到管理员姓名
		$field['text'] = $followText;
		//当天是否提交相同内容的跟进信息
		$date      = date('Y-m-d');
		$repeatTxt = sqlNum("follow", " stid = '" . self::$stid . "' and target = '$field[target]' and targetId = '$field[targetId]' and text = '$followText' and time > '$date' ");
		//是否存在相同的下次跟进日期提醒计划
		$repeatNum = sqlNum("backlog", " stid = '" . self::$stid . "' and type = '$backlogType' and typeId = '$field[targetId]' and startDay = '" . $startDay . "' ");
		//判断
		if (!empty($startDay) and $startDay < $date) {
			$this->resp['warn'] = "下次跟进日期不得小于今天";
		} elseif (!empty($startDay) and $repeatNum > 0) {
			$this->resp['warn'] = "存在相同的下次跟进日期提醒计划";
		} elseif ($repeatTxt > 0) {
			$this->resp['warn'] = "你当天不能提交相同内容的跟进信息";
		} else {
			if (!$this->power(self::page, "newFollow")) {
				$this->resp['warn'] = "你没有新增客户跟进的权限";
			} else {
				$kehu = query("kehu", " khid = '$field[targetId]' ");
				if (empty($kehu['khid'])) {
					$this->resp['warn'] = "未找到此客户";
					return;
				}
				//更新客户更新时间
				static::update([
					"table" => "kehu",
					"field" => ["lastFollowTime" => date("Y-m-d H:i:s")],
					"where" => " khid = '$field[targetId]' ",
				]);
				$kehuStaff            = query('kehu_staff', "id = '{$field['kehuStaffId']}'");
				$field['kehuStaffId'] = $kehuStaff['id'];
				$field['contactName'] = $kehuStaff['name'];
				$field['targetName']  = $kehu['companyName'] ?: '';
				$this->resp['warn']   = static::insert(["table" => "follow", "field" => $field]);
				if ($this->resp['warn'] == "新增成功") {
					if ($this->post('workFlow')) {
						update([
							'table' => 'kehu',
							'field' => ['workFlow' => $this->post('workFlow')], 'where' => "khid = '$field[targetId]'",
						]);
					}
					//结束代办事项
					backlogEnd(["stid" => $this->control['stid'], "typeId" => $field['targetId']]);
					//如果有提交下次跟进日
					if (!empty($startDay)) {
						backlogIn([
							"stid"      => $this->control['stid'],
							"type"      => $backlogType,
							"typeId"    => $field['targetId'],
							"text"      => "你有一个" . $field['target'] . "【" . $kehu['companyName'] . "】需要跟进",
							"startDay"  => $startDay,
							"targetCla" => 'client',
							"targetFun" => 'detail',
						]);
					}
					//添加日志
					$text = $this->control['name'] . "新增了一条跟进：" . $field['target'] . "【" . $field['targetId'] . "】：" . $this->post('text');
					$this->logText(["type" => "talentPool", "text" => $text]);
					$this->code = 1;
				}
			}
		}
	}
	
	/**
	 * 访客计划列表
	 *
	 * @return void
	 */
	public function visitPlanList()
	{
		$this->code       = 1;
		$date             = $this->post('date');
		$where            = search([
			'=' => [
				"locationDate" => $this->post('date') ?: $this->date, # 日期
				"stid"         => $this->post('stid') ?: self::$stid,
			],
		]);
		$page             = $this->page([
			"table" => "visit_plan",
			"where" => $where,
			"order" => "time desc",
		]);
		$data['calendar'] = self::calendar($date);
		$result           = [];
		foreach ($page['array'] as $item) {
			$item['startTimeFormat'] = str_replace(['AM', 'PM'], ['上午', '下午'], self::formatDate($item['startTime'], 'A H:i'));
			$item['endTimeFormat']   = str_replace(['AM', 'PM'], ['上午', '下午'], self::formatDate($item['endTime'], 'A H:i'));
			$result[]                = $item;
		}
		$data['result'] = $result;
		
		$data['page']       = $page['para'];
		$this->resp['data'] = $data;
	}
	
	/**
	 * 日历
	 *
	 * @return array
	 */
	public static function calendar($date = '')
	{
		//数据查询
		$date     = $date ?: date('Y-m-d');
		$month    = date('Y-m', strtotime($date));//月份
		$days     = date('t', strtotime($date));  //此月份总天数
		$dayArr   = [];
		$now_week = date('w', strtotime(date('Y-m-01', strtotime($date))));
		for ($i = 0; $i < $now_week; $i++) {
			$dayArr[] = [
				'index' => ' ',
				'date'  => ' ',
				'tag'   => 0,
			];
		}
		// 日期循环
		for ($i = 1; $i <= $days; $i++) {
			$today    = $month . '-' . sprintf("%02d", $i);
			$info     = query('visit_plan', " stid = '" . self::$stid . "' and locationDate = '$today' ", 'id');
			$dayArr[] = [
				'index' => $i,
				'date'  => $today,
				'tag'   => empty($info['id']) ? 0 : 1,
			];
		}
		$weekArray = ["日", "一", "二", "三", "四", "五", "六"];
		return [
			'date'        => $date,
			'month'       => $month,
			'currentDate' => date('m月d日', strtotime($date)) . ' 周' . $weekArray[date("w", strtotime($date))] . ' ' . ($date == date('Y-m-d') ? '(今天)' : ''),
			'list'        => $dayArr,
		];
	}
	
	/**
	 * 访客计划
	 *
	 * @return void
	 */
	public function visitPlanEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'theme'        => $this->post('theme'),
			'khid'         => $this->post('khid'),
			'startTime'    => $this->post('startTime'),
			'endTime'      => $this->post('endTime'),
			'locationDate' => $this->post('date') ?: date('Y-m-d'),
			'remindTime'   => $this->post('remindTime'),
			'member'       => $this->post('member') ?: '',
			'address'      => $this->post('address'),
			'text'         => $this->post('text'),
		];
		$annotation = [
			'theme'     => '主题',
			'startTime' => '计划时间',
			'endTime'   => '计划时间',
		];
		$rules      = [
			'theme'     => 'required',
			'startTime' => 'required',
			'endTime'   => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (!$this->checkRemindTime($field['remindTime'], $field['startTime'])) {
			$this->resp['warn'] = '当前提醒方式不满足当前计划开始时间';
		} else {
			$where                    = " id = '$id' ";
			$info                     = query('visit_plan', $where);
			$field['startRemindTime'] = self::startRemindTime($field['remindTime'], $field['startTime']);
			if (!$info['id']) {
				$field              = array_merge($field, [
					'id'   => $id,
					'stid' => self::$stid,
				]);
				$this->resp['warn'] = static::insert(["table" => 'visit_plan', "field" => $field,]);
			} else {
				$this->resp['warn'] = static::update([
					"table" => 'visit_plan',
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => 'visitPlan', "text" => $text]);
				$this->code = 1;
			}
		}
		
		resp:
	}
	
	/**
	 * 访客计划详情
	 *
	 * @return void
	 */
	public function detailVisitPlan()
	{
		$id    = $this->post('id');
		$field = '`id`, `khid`, `theme`, `startTime`, `endTime`, `remindTime`, `member`, `address`, `locationDate`, `factStartTime`, `factEndTime`, `achievement`, `signAddress`, `text`, `startRemindTime`, `stid`';
		$info  = query('visit_plan', " id = '$id' ", $field);
		if ($info['stid'] != self::$stid) {
			$this->resp['warn'] = '这不是您的访客计划';
		} elseif (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此访客计划";
		} else {
			$result              = self::sqlFind("SELECT id, name, concat('" . root . "', src) as url FROM `file`  WHERE targetId = '$id' ");
			$info['file']        = $result;
			$kehu                = query('kehu', " khid = '{$info['khid']}'", 'companyName');
			$staffAll            = self::staffAll($info['member']);
			$info['member']      = $staffAll['all'];
			$info['memberId']    = $staffAll['id'];
			$info['memberName']  = $staffAll['name'];
			$info['companyName'] = $kehu['companyName'];
			$data                = $info;
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * 删除访客计划
	 */
	public function deleteVisitPlan()
	{
		$array = $this->post('listId') ?: $this->post('id');
		if (!$this->power('visitPlan', "del")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query('visit_plan', " id = '$id' ");
				if ($info['stid'] != self::$stid) {
					//返回
					$this->resp['warn'] = "删除失败：这不是您的访客计划";
				} else {
					$result = find(['table' => 'file', 'where' => "targetId = '$id'"]);
					foreach ($result['array'] as $file) {
						fileDelete($file['src']);
					}
					//删除附件
					delete(["table" => "file", "where" => " targetId = '$id' "]);
					//删除待办
					delete(["table" => "backlog", "where" => " typeId = '$id' "]);
					//最后删除基本参数
					delete(["table" => 'visit_plan', "where" => " id = '$id' "]);
					$x++;
				}
				$text .= "访客计划 ID【" . $info['id'] . "】删除成功。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => 'visitPlan', "text" => $text]);
			$this->code         = 1;
			$this->resp['warn'] = "删除了" . $x . "条访客计划，详情见系统日志。";
		}
	}
	
	
	/**
	 * 成果编辑
	 */
	public function visitPlanResultEdit()
	{
		// 文件id
		$fileIdArr  = $this->post('fileId') ? explode(',', $this->post('fileId')) : '';
		$id         = $this->post('id');
		$timeArr    = explode(' ~ ', $this->post('factTime'));
		$field      = [
			'factStartTime' => $timeArr[0],
			'factEndTime'   => $timeArr[1],
			'achievement'   => $this->post('achievement'),
		];
		$annotation = [
			'achievement'   => '成果',
			'factStartTime' => '实际时间',
			'factEndTime'   => '实际时间',
		];
		$rules      = [
			'achievement'   => 'required',
			'factStartTime' => 'required',
			'factEndTime'   => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$info = query('visit_plan', "id = '$id'");
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此日程';
		} elseif (strtotime($field['factEndTime']) <= strtotime($field['factStartTime'])) {
			$this->resp['warn'] = '结束时间不能小于开始时间';
		} elseif (strtotime($field['factEndTime']) > time()) {
			$this->resp['warn'] = '实际结束时间不能早于当前时间';
		} else {
			$this->resp['warn'] = static::update([
				"table" => 'visit_plan',
				"field" => $field,
				"where" => " id = '$id'",
			]);
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				if (is_array($fileIdArr)) {
					update([
						'table' => 'file',
						'field' => ['targetId' => $id],
						'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')",
					]);
				}
				//清除待办
				backlogEnd(array(
					"stid"   => self::$stid,
					"typeId" => $id,
				));
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "成果， id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				$this->code = 1;
			}
		}
		resp:
	}
	
	
	/**
	 * 转到公客池
	 *
	 * @return void
	 */
	public function poolEdit()
	{
		$this->code = 0;
		$listId     = $this->post('khid') ? [$this->post('khid')] : $this->post('listId');
		$poolId     = $this->post('poolId') ?: self::defaultPool;
		$pool       = query('pool', "id = '$poolId'");
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '您还没有' . self::title . '的编辑权限';
		} elseif (empty($listId) || !is_array($listId)) {
			$this->resp['warn'] = '未找到需要转到客户池的客户';
		} elseif (empty($pool['id'])) {
			$this->resp['warn'] = '未找到客户池';
		} else {
			$x = 0;
			foreach ($listId as $id) {
				//客户
				$info = query(self::table, " khid = '$id'");
				if ($info['manager'] == self::$stid) {
					$warn = update(array(
						'table' => self::table,
						'field' => [
							'manager'      => '',
							'collaborator' => '',
							'see'          => '',
							'poolId'       => $pool['id'],
						],
						'where' => "khid = '$id'",
					));
					if (in_array($warn, ['新增成功', '更新成功'])) {
						$x++;
						$text = $this->control['name'] . "把" . self::title . "【{$info['companyName']}】， id：【" . $id . '】添加到了客户池【' . $pool['name'] . '】';
						$this->logText(["type" => self::page, "text" => $text]);
						//日志
						$this->logWrite($id, '添加到客户池', $this->control['name'] . "把客户添加到了客户池【{$pool['name']}】");
					}
					$this->code = 1;
				} else {
					$text = $this->control['name'] . "把" . self::title . "【{$info['companyName']}】添加到客户池失败：不是负责人";
					$this->logText(["type" => self::page, "text" => $text]);
				}
			}
			$this->resp['warn'] = "成功将" . $x . '个客户添加到了客户池';
		}
	}
	
	/**
	 * 检查提前提醒时间和计划开始时间是否有冲突
	 *
	 * @param $type
	 * @param $startTime
	 * @return bool|int
	 */
	protected static function checkRemindTime($type, $startTime): bool|int
	{
		return match ($type) {
			'15分钟前' => time() < strtotime($startTime) - 15 * 60,
			'日程开始时' => time() < strtotime($startTime),
			'1小时前'  => time() < strtotime($startTime) - 60 * 60,
			'1天前'   => time() < strtotime($startTime) - 60 * 60 * 24,
			default => true,
		};
	}
	
	/**
	 * 添加消息
	 *
	 * @param $type
	 * @param $startTime
	 * @return string
	 */
	protected static function startRemindTime($type, $startTime): string
	{
		return match ($type) {
			'15分钟前' => date('Y-m-d H:i:s', strtotime($startTime) - 15 * 60),
			'日程开始时' => $startTime,
			'1小时前'  => date('Y-m-d H:i:s', strtotime($startTime) - 60 * 60),
			'1天前'   => date('Y-m-d H:i:s', strtotime($startTime) - 24 * 60 * 60),
			default => '',
		};
	}
	
	/**
	 * 根据坐标解析出地址
	 *
	 * @param $lat
	 * @param $lng
	 * @return array
	 */
	public static function coordinateToAddr($lat, $lng): array
	{
		$key          = para('tencentMapKey');
		$res          = self::curlGet("https://apis.map.qq.com/ws/geocoder/v1/?location=" . $lat . ',' . $lng . "&key=" . $key);
		$res          = json_decode($res, true);
		$data['data'] = [];
		$data['warn'] = 'ok';
		if ($res['status'] == 0) {
			$data['data']     = $res['result'];
			$data['err_code'] = 0;
		} else {
			$data['err_code'] = 1;
			$data['warn']     = '请求数据失败：' . json_encode($res, 320);
		}
		return $data;
	}
	
	/**
	 * 删除
	 *
	 * @return void
	 */
	public function delete(): void
	{
		$array = $this->post('listId') ?: $this->post('id');
		if (!$this->power(self::page, "del")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['manager'] != self::$stid) {
					$warn = "删除失败：这不是您的客户";
				} else {
					$result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
					foreach ($result['array'] as $file) {
						fileDelete($file['src']);
					}
					//删除附件
					delete(array("table" => "file", "where" => " targetId = '$id' "));
					//删除标签
					delete(array("table" => "kehu_label", "where" => " targetId = '$id' "));
					//删除跟进记录
					delete(array("table" => "follow", "where" => " targetId = '$id' "));
					//删除操作日志
					delete(array("table" => "clue_log", "where" => " orderId = '$id' "));
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " khid = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->resp['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$this->code         = 1;
		}
	}
	
	/**
	 * 删除联系人
	 *
	 * @return void
	 */
	public function delContacts(): void
	{
		$array = $this->post('id') ? explode(',', $this->post('id')) : '';
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$kehuStaff = query("kehu_staff", " id = '$id'");
				$kehu      = query("kehu", " khid = '$kehuStaff[khid]' ");
				//删除客户联系人基本参数
				delete(["table" => "kehu_staff", "where" => " id = '$id' "]);
				//添加日志
				$text = $this->control['name'] . "删除了一个客户的联系人：<br>
				公司名称：" . kong($kehu['companyName']) . "<br>
				职位：" . $kehuStaff['position'] . "<br>
				姓名：" . $kehuStaff['name'] . "<br>
				手机：" . $kehuStaff['tel'];
				$this->logText(["type" => "client", "text" => $text]);
				$x++;
			}
			$this->resp['warn'] = "删除了" . $x . "个客户联系人，详情见系统日志。";
			$this->code         = 1;
		}
	}
	
	/**
	 * 删除客户跟进
	 *
	 * @return void
	 */
	public function delFollow(): void
	{
		$array = $this->post('id') ? explode(',', $this->post('id')) : '';
		if (!$this->power('client', "delFollow")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query('follow', " id = '$id' AND target='客户' ");
				if (!empty($info['id'])) {
					delete(["table" => "follow", "where" => "id = '$id' "]);
					$x++;
				}
				$text .= $this->control['name'] . "删除了一条跟进：" . $info['text'] . "。<br>";
			}
			//添加日志
			$this->logText(["type" => 'follow', "text" => $text]);
			$this->resp['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$this->code         = 1;
		}
	}
	
	/**
	 * 详情
	 *
	 * @return void
	 */
	public function detail()
	{
		$id   = $this->post('khid');
		$info = query(self::table, " khid = '" . $id . "'");
		if (!in_array(self::$stid, explode(',', $info['see']))) {
			$this->resp['warn'] = '这不是您的' . self::title;
		} elseif (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['khid'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} else {
			$data            = [];
			$data['info']    = [
				'khid'            => $info['khid'],
				'companyName'     => $info['companyName'],
				'contactTel'      => $info['contactTel'],
				'contactName'     => $info['contactName'],
				'workFlow'        => $info['workFlow'],
				'time'            => self::formatDate($info['time'], 'm月d日 H:i'),
				'manager'         => self::findStaff($info['manager']),
				'nature'          => $info['nature'],
				'contactIdentity' => $info['contactIdentity'],
				'landline'        => $info['landline'],
				'contactWx'       => $info['contactWx'],
				'contactQQ'       => $info['contactQQ'],
				'website'         => $info['website'],
				'email'           => $info['email'],
				'address'         => $info['address'],
				'birthDay'        => $info['birthDay'],
			];
			$pool            = query('pool', " id = '{$info['poolId']}' ");
			$staffAll        = self::staffAll($info['collaborator']);
			$data['manage']  = [
				'level'            => $info['level'],
				'classify'         => $info['classify'],
				'industry'         => $info['industry'],
				'scale'            => $info['scale'],
				'source'           => $info['source'],
				'tags'             => self::filterArray(explode(',', $info['tags'])),
				'tagArr'           => self::sqlFind("SELECT tag_detail_id as id, d.name as name FROM `kehu_label` as l, tag_detail as d WHERE l.tag_detail_id=d.id AND `targetId` = '$info[khid]'"),
				'workFlow'         => $info['workFlow'],
				'followTime'       => $info['followTime'],
				'poolId'           => $info['poolId'],
				'poolName'         => $pool['name'],
				'managerName'      => self::findStaff($info['manager']),
				'manager'          => $info['manager'],
				'collaboratorName' => $staffAll['name'],
				'collaboratorId'   => $staffAll['id'],
				'collaborator'     => $staffAll['all'],
				'text'             => $info['text'],
			];
			$data['invoice'] = [
				'invoiceCompany' => $info['invoiceCompany'],
				'companyBank'    => $info['companyBank'],
				'companyBankNum' => $info['companyBankNum'],
				'companyAddress' => $info['companyAddress'],
				'companyNum'     => $info['companyNum'],
				'postAddress'    => $info['postAddress'],
			];
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * @param $id
	 * @return array
	 */
	private static function staffAll($id)
	{
		$idArr   = self::filterArray(explode(',', $id));
		$nameStr = self::findStaff($idArr);
		$nameArr = self::filterArray(explode('，', $nameStr));
		$data    = [];
		foreach ($idArr as $key => $id) {
			$data[] = [
				'id'   => $id,
				'name' => $nameArr[$key],
			];
		}
		
		return [
			'id'   => $idArr,
			'name' => $nameArr,
			'all'  => $data,
		];
	}
	
	/**
	 * 客户联系人详情
	 *
	 * @return void
	 */
	public function detailStaff()
	{
		$khid = $this->post('khid');
		$id   = $this->post('id');
		$info = query(self::tableStaff, " khid = '$khid' AND id = '$id' ");
		if (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此客户联系人";
		} else {
			$kehu = query('kehu', " khid = '{$info['khid']}'  ");
			if (!in_array(self::$stid, explode(',', $kehu['see']))) {
				$this->resp['warn'] = '这不是您的' . self::title;
			} else {
				unset($info['time'], $info['updateTime']);
				$info['companyName'] = $kehu['companyName'];
				$data                = $info;
				//返回
				$this->code         = 1;
				$this->resp['data'] = $data;
			}
		}
	}
	
	public function tabs()
	{
		$id   = $this->post('khid');
		$act  = $this->post('act');
		$info = query(self::table, " khid = '" . $id . "'");
		if (!in_array(self::$stid, explode(',', $info['see']))) {
			$this->resp['warn'] = '这不是您的' . self::title;
		} elseif (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['khid'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} else {
			$root = root;
			$sql  = match ($act) {
				'file'      => "SELECT `id`, `name`, `format`, concat('" . root . "', src) as `url` FROM `file` WHERE target = '客户' and targetId = '$id'",
				'follow'    => "SELECT `id`, s.name as `staffName`, concat('$root', s.ico) as `ico`, `targetName`, `contactName`, `followType`, f.text, f.time FROM `follow` as f, `staff` as s WHERE s.stid = f.stid AND target = '客户' and targetId = '$id' ",
				'visitPlan' => "SELECT `id`, `theme`, `member`, `achievement`, `text`, stid, time FROM `visit_plan` WHERE khid = '$id' ",
				default     => "SELECT `id`, `name`, `sex`, `tel`, `department`, `position`,  `phone`, `qq`, `WeChat`, `birthDay`, `address`, `text` FROM `kehu_staff` WHERE khid = '$id' ",
			};
			$data = self::sqlFind($sql);
			switch ($act) {
				case 'visitPlan':
					foreach ($data as $key => $item) {
						$staff                   = query('staff', " stid = '$item[stid]' ", ' name, ico');
						$data[$key]['staffName'] = $staff['name'];
						$data[$key]['staffIco']  = $staff['ico'] ? root . $staff['ico'] : '';
						$data[$key]['time']      = self::formatDate($item['time'], 'm月d日 H:i');
						$data[$key]['member']    = self::findStaff(explode(',', $item['member']));
						$data[$key]['ico']       = self::findStaff(explode(',', $item['member']), 'ico');
						$data[$key]['root']      = root;
					}
					break;
				case 'follow':
					foreach ($data as $key => $item) {
						$data[$key]['time'] = self::formatDate($item['time'], 'm月d日 H:i');
					}
					break;
				default:
					$data = array_merge([
						[
							'id'   => 'frequent',
							'name' => $info['contactName'],
						],
					], $data);
					break;
			}
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * 客户资料排重
	 *
	 * @param $data
	 * @return bool|string
	 */
	public static function repeat($data): bool|string
	{
		foreach ($data['name'] as $name => $explain) {
			if (!empty($data['field'][$name])) {
				//客户排重查询
				$kehu = query("kehu", $name . " = '" . $data['field'][$name] . "' and khid != '$data[khid]' ");
				if (!empty($kehu['khid'])) {
					if ($kehu['stid'] == "公客") {
						$follow = "此客户为公客";
					} else {
						$staff  = query("staff", " stid = '$kehu[stid]' ");
						$follow = "跟进人【" . $staff['name'] . "】";
					}
					return "【" . $kehu['companyName'] . "】存在相同的" . $explain . "【" . $data['field'][$name] . "】" . $follow;
				}
			}
		}
		return false;
	}
	
	/**
	 * 地址解析
	 *
	 * @return void
	 */
	public function latLngToAddr()
	{
		$field      = [
			'lat' => $this->post('lat'),
			'lng' => $this->post('lng'),
		];
		$annotation = [
			'lat' => '地址信息',
			'lng' => '地址信息',
		];
		$rules      = [
			'lat' => 'required',
			'lng' => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
		} else {
			$this->code = 1;
			$res        = self::coordinateToAddr($field['lat'], $field['lng']);
			$this->code = ($res['err_code'] === 0) ? 1 : 0;
			unset($res['err_code']);
			$this->resp = $res;
		}
	}
	
	/**
	 * 访客签到
	 *
	 * @return void
	 */
	public function visitPlanSign()
	{
		$field      = [
			'id'  => $this->post('id'),
			'lat' => $this->post('lat'),
			'lng' => $this->post('lng'),
		];
		$annotation = [
			'id'  => '访客计划id',
			'lat' => '地址信息',
			'lng' => '地址信息',
		];
		$rules      = [
			'id'  => 'required',
			'lat' => 'required',
			'lng' => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
		} else {
			$where = " stid = '" . self::$stid . "' and id = '{$field['id']}' ";
			$info  = query('visit_plan', $where);
			if (empty($info['id'])) {
				$this->resp['warn'] = '访客计划不存在';
				goto  resp;
			}
			$res = self::coordinateToAddr($field['lat'], $field['lng']);
			if ($res['err_code'] === 1) {
				$this->resp['warn'] = '签到失败，服务错误';
			} else {
				$field['signAddress'] = $res['data']['address'];
				unset($field['id']);
				$warn = static::update([
					'table' => 'visit_plan',
					'field' => $field,
					'where' => $where,
				]);
				if ($warn !== '更新成功') {
					$this->resp['warn'] = '签到失败，系统错误';
				} else {
					$this->code         = 1;
					$this->resp['warn'] = '签到成功';
				}
			}
		}
		
		resp:
	}
	
	
	/**
	 * 日志写入
	 */
	public function logWrite($id, $type, $text = '')
	{
		$info = query(self::table, " khid = '$id'");
		insert(array(
			'table' => 'clue_log',
			'field' => [
				'id'        => self::getId(),
				'orderId'   => $id,
				'classify'  => '客户',
				'type'      => $type,
				'text'      => $text ?: $this->control['name'] . $type . '了客户【' . $info['companyName'] . '】',
				'staffName' => $this->control['name'],
				'stid'      => self::$stid,
				'time'      => $this->time,
			],
		));
	}
}
